import json
import google.protobuf.json_format as json_format

import coin.exchange.base.kr_rest.private_client_base as privcb
from cc.appcoin2.support.order.py_parser import PyOrderParser
from coin.exchange.bitbank.kr_rest.native_private_client import (
    BitbankNativePrivateClient)
from coin.exchange.bitbank.kr_rest.product_info import bitbank_product_info
from coin.proto.coin_query_pb2 import AccountBalance
from coin2.exchange.order.system_pb2 import OrderSystemConfig
from coin2.exchange.symbology_pb2 import ProductConfig


class BitbankPrivateClient(privcb.PrivateClientBase):
  def __init__(self, key_file, timeout=5):
    privcb.PrivateClientBase.__init__(self)
    self.nprivc = BitbankNativePrivateClient(key_file=key_file, timeout=timeout)
    pi_bundle = bitbank_product_info._product_infos
    assert pi_bundle.HasField('mea')
    oss_config = OrderSystemConfig(
        mea=pi_bundle.mea,
        products=ProductConfig(norms=[pi.symbol for pi in pi_bundle.product_infos]))
    self._parser = PyOrderParser.from_mea_str(pi_bundle.mea)
    self._parser.add_product(oss_config.SerializeToString())

  def query_account_balance_impl(self):
    update = self.nprivc.query_asset()
    msg = self._parser.parse_account_balance(json.dumps(update.msg))
    account_balance = AccountBalance()
    json_format.Parse(msg, account_balance)
    update.msg = account_balance
    return update

  def query_cancel_product_impl(self, product):
    raise NotImplementedError

  def query_fills_impl(self, product):
    raise NotImplementedError

  def query_submit_impl(self, product, side, price, qty):
    raise NotImplementedError


if __name__ == "__main__":
  client = BitbankPrivateClient(
      key_file='../../coin_key/view/xunke00/bitbank/view_key.json')
  print(client.query_account_balance().msg)
